<template>
  <main class="flex-1 max-w-7xl mx-auto w-full px-4 sm:px-6 lg:px-8 py-8">
    <!-- 标题区域 -->
    <div class="text-center mb-8">
      <h1
        class="text-3xl font-bold mb-2 transition-colors duration-200"
        style="color: var(--text-primary)"
      >
        MCP <span class="text-gradient">JSON</span> 到
        <span class="text-gradient">TOML</span> 转换工具
      </h1>
      <p class="text-lg transition-colors duration-200" style="color: var(--text-secondary)">
        将 MCP 配置文件从 JSON 格式转换为 TOML 格式
      </p>
    </div>

    <!-- 编辑器区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
      <!-- JSON输入编辑器 -->
      <div class="editor-container flex flex-col h-96 relative">
        <div class="editor-header flex items-center justify-between">
          <div class="flex items-center">
            <h3 class="editor-title">JSON 输入</h3>
            <!-- 验证状态指示器 -->
            <div
              v-if="validationStatus && validationStatus !== 'idle' && inputContent.trim()"
              class="flex items-center text-sm ml-2 transition-colors duration-200"
              :style="{
                color: validationStatus === 'valid' ? 'var(--success-600)' : 'var(--error-600)',
              }"
            >
              <svg
                v-if="validationStatus === 'valid'"
                class="w-4 h-4 mr-1"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M5 13l4 4L19 7"
                />
              </svg>
              <svg
                v-else
                class="w-4 h-4 mr-1"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
              {{ validationStatus === 'valid' ? '格式正确' : '格式错误' }}
            </div>
          </div>

          <!-- 清空输入按钮 -->
          <button
            @click="clearInput"
            class="p-2 rounded-md shadow-sm transition-all duration-200 hover:shadow-md hover:scale-105 active:scale-95"
            style="
              color: var(--text-tertiary);
              background-color: var(--bg-primary);
              border: 1px solid var(--border-primary);
            "
            :style="{
              color: isDark ? 'var(--text-tertiary)' : 'var(--text-tertiary)',
            }"
            title="清空输入"
            aria-label="清空输入内容"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
              />
            </svg>
          </button>
        </div>
        <div class="relative flex-1 min-h-0">
          <textarea
            v-model="inputContent"
            @input="validateInput"
            class="w-full h-full p-4 font-mono text-sm border-0 resize-none focus:outline-none custom-scrollbar transition-colors duration-200"
            :style="{
              backgroundColor: 'var(--bg-primary)',
              color: validationStatus === 'invalid' ? 'var(--error-600)' : 'var(--text-primary)',
            }"
            placeholder="在此输入JSON格式的MCP配置..."
            spellcheck="false"
            aria-label="JSON输入编辑器"
          ></textarea>
        </div>
      </div>

      <!-- TOML输出编辑器 -->
      <div class="editor-container flex flex-col h-96 relative">
        <div class="editor-header flex items-center justify-between">
          <div class="flex items-center">
            <h3 class="editor-title">TOML 输出</h3>
            <!-- 转换状态指示器 -->
            <div
              v-if="outputContent && conversionStatus === 'success'"
              class="flex items-center text-sm ml-2 transition-colors duration-200"
              style="color: var(--success-600)"
            >
              <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M5 13l4 4L19 7"
                />
              </svg>
              转换成功
            </div>
          </div>

          <!-- 复制结果按钮 -->
          <button
            @click="copyOutput"
            :disabled="!outputContent.trim()"
            class="p-2 rounded-md shadow-sm transition-all duration-200 hover:shadow-md hover:scale-105 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100"
            style="
              color: var(--text-tertiary);
              background-color: var(--bg-primary);
              border: 1px solid var(--border-primary);
            "
            title="复制结果"
            aria-label="复制TOML输出内容"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
              />
            </svg>
          </button>
        </div>
        <div class="relative flex-1 min-h-0">
          <textarea
            v-model="outputContent"
            readonly
            class="w-full h-full p-4 font-mono text-sm border-0 resize-none focus:outline-none custom-scrollbar transition-colors duration-200"
            style="background-color: var(--bg-primary); color: var(--text-primary)"
            placeholder="转换后的TOML格式将显示在这里..."
            spellcheck="false"
            aria-label="TOML输出编辑器"
          ></textarea>
        </div>
      </div>
    </div>

    <!-- 转换错误提示 -->
    <div
      v-if="conversionError && conversionStatus === 'error'"
      class="mb-6 p-2 rounded-md text-sm transition-all duration-200"
      style="
        background-color: var(--error-50);
        border: 1px solid var(--error-200);
        color: var(--error-700);
      "
    >
      <div class="flex items-start">
        <svg
          class="w-4 h-4 mr-1 mt-0.5 shrink-0"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
          />
        </svg>
        <div>
          <div class="font-medium">转换错误</div>
          <div class="text-xs mt-1">{{ conversionError.message }}</div>
        </div>
      </div>
    </div>

    <!-- 转换按钮 -->
    <div class="flex justify-center mb-6">
      <div class="flex items-center space-x-4">
        <!-- Windows环境变量复选框 -->
        <div class="relative group">
          <label class="flex items-center space-x-2 cursor-pointer">
            <input
              v-model="addWindowsEnv"
              type="checkbox"
              class="w-4 h-4 rounded focus:ring-2 transition-colors duration-200"
              style="
                accent-color: var(--primary-600);
                border-color: var(--border-primary);
                background-color: var(--bg-primary);
                color: var(--text-primary);
              "
            />
            <span
              class="text-sm transition-colors duration-200"
              style="color: var(--text-secondary)"
            >
              添加 Windows 环境变量
            </span>
          </label>

          <!-- 工具提示 -->
          <div
            class="absolute bottom-full left-0 mb-2 px-3 py-2 text-xs rounded-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 w-64 z-10"
            style="
              background-color: var(--neutral-800);
              color: var(--text-inverse);
              border: 1px solid var(--border-primary);
            "
          >
            <div
              class="absolute top-full left-4 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent"
              :style="{ borderTopColor: 'var(--neutral-800)' }"
            ></div>
            选中此项将添加Windows环境变量和启动超时配置，确保MCP服务器在Windows环境下正常启动。
          </div>
        </div>

        <button
          @click="convertContent"
          :disabled="!inputContent.trim() || isConverting || validationStatus === 'invalid'"
          class="btn btn-primary disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100 flex items-center transition-all duration-200"
        >
          <svg
            v-if="isConverting"
            class="w-4 h-4 mr-2 loading-spinner"
            fill="none"
            viewBox="0 0 24 24"
          >
            <circle
              class="opacity-25"
              cx="12"
              cy="12"
              r="10"
              stroke="currentColor"
              stroke-width="4"
            ></circle>
            <path
              class="opacity-75"
              fill="currentColor"
              d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
            ></path>
          </svg>
          <svg v-else class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"
            />
          </svg>
          {{ isConverting ? '转换中...' : '转换' }}
        </button>
      </div>
    </div>

    <!-- 示例配置 -->
    <div
      class="rounded-lg shadow-sm p-6 transition-all duration-200 overflow-hidden"
      style="background-color: var(--bg-primary); border: 1px solid var(--border-primary)"
    >
      <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-6">
        <h3
          class="text-lg font-semibold transition-colors duration-200"
          style="color: var(--text-primary)"
        >
          常见配置示例
        </h3>
        <div class="mt-2 sm:mt-0 flex items-center text-sm" style="color: var(--text-tertiary)">
          <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
            <path
              fill-rule="evenodd"
              d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
              clip-rule="evenodd"
            />
          </svg>
          <span> 点击示例加载配置</span>
        </div>
      </div>

      <!-- 桌面端水平滚动布局 -->
      <div class="hidden sm:block">
        <div class="flex space-x-4 overflow-x-auto pb-2 scrollbar-hide">
          <div
            v-for="example in examples"
            :key="example.name"
            @click="loadExample(example)"
            class="example-card-horizontal shrink-0 w-80 transition-all duration-200"
            :style="{ minWidth: '320px' }"
          >
            <div class="flex items-start space-x-3">
              <div
                class="shrink-0 w-10 h-10 rounded-lg flex items-center justify-center"
                :style="getExampleIconStyle(example.category)"
              >
                <svg class="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
                  <path
                    v-if="example.category === 'git'"
                    d="M12.316 3.051a1 1 0 01.633 1.265l-4.12 2.055a1 1 0 01-.89 0L4.22 4.316a1 1 0 11-.894-1.789l4.12-2.055a3 3 0 012.67 0l4.12 2.055a1 1 0 01-.633 1.265l-4.12-2.055a1 1 0 00-.89 0l-4.12 2.055z"
                  />
                  <path
                    v-else-if="example.category === 'filesystem'"
                    d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z"
                  />
                  <path
                    v-else-if="example.category === 'database'"
                    d="M3 12v3c0 1.657 3.134 3 7 3s7-1.343 7-3v-3c0 1.657-3.134 3-7 3s-7-1.343-7-3z"
                  />
                  <path
                    v-else-if="example.category === 'search'"
                    d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
                  />
                  <path
                    v-else-if="example.category === 'storage'"
                    d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z"
                  />
                  <path
                    v-else
                    d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z"
                  />
                </svg>
              </div>
              <div class="flex-1 min-w-0">
                <h4 class="example-title truncate">{{ example.name }}</h4>
                <p class="example-description line-clamp-2">{{ example.description }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 移动端网格布局 -->
      <div class="sm:hidden grid grid-cols-1 gap-3">
        <div
          v-for="example in examples"
          :key="example.name"
          @click="loadExample(example)"
          class="example-card-mobile transition-all duration-200"
        >
          <div class="flex items-center space-x-3">
            <div
              class="shrink-0 w-8 h-8 rounded-lg flex items-center justify-center"
              :style="getExampleIconStyle(example.category)"
            >
              <svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
                <path
                  v-if="example.category === 'git'"
                  d="M12.316 3.051a1 1 0 01.633 1.265l-4.12 2.055a1 1 0 01-.89 0L4.22 4.316a1 1 0 11-.894-1.789l4.12-2.055a3 3 0 012.67 0l4.12 2.055a1 1 0 01-.633 1.265l-4.12-2.055a1 1 0 00-.89 0l-4.12 2.055z"
                />
                <path
                  v-else-if="example.category === 'filesystem'"
                  d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z"
                />
                <path
                  v-else-if="example.category === 'database'"
                  d="M3 12v3c0 1.657 3.134 3 7 3s7-1.343 7-3v-3c0 1.657-3.134 3-7 3s-7-1.343-7-3z"
                />
                <path
                  v-else-if="example.category === 'search'"
                  d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
                />
                <path
                  v-else-if="example.category === 'storage'"
                  d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z"
                />
                <path
                  v-else
                  d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z"
                />
              </svg>
            </div>
            <div class="flex-1 min-w-0">
              <h4 class="example-title text-sm truncate">{{ example.name }}</h4>
              <p class="example-description text-xs line-clamp-1">{{ example.description }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { jsonToToml } from '@/utils/converter'
import { validateJson } from '@/utils/validator'
import { useClipboardState } from '@/composables/useClipboard'
import { useTheme } from '@/composables/useTheme'
import { useCopyToast } from '@/composables/useCopyToast'
import type { McpExample, ConversionStatus, ValidationError, ConversionError } from '@/types'

// 主题
const { isDark } = useTheme()

// 复制提示
const { showSuccess, showError } = useCopyToast()

// 状态
const inputContent = ref('')
const outputContent = ref('')
const conversionStatus = ref<ConversionStatus>('idle')
const validationError = ref<ValidationError | null>(null)
const conversionError = ref<ConversionError | null>(null)
const addWindowsEnv = ref(false)
const isConverting = ref(false)
const validationStatus = ref<'idle' | 'valid' | 'invalid'>('idle')

// 剪贴板
const { copy } = useClipboardState()

// 示例配置 - 涵盖所有合规性场景
const examples: McpExample[] = [
  // 标准配置示例
  {
    name: 'GitHub 服务器',
    description: 'GitHub MCP 服务器标准配置',
    json: JSON.stringify(
      {
        mcpServers: {
          github: {
            command: 'npx',
            args: ['-y', '@modelcontextprotocol/server-github'],
            env: {
              GITHUB_PERSONAL_ACCESS_TOKEN: 'your_token_here',
            },
          },
        },
      },
      null,
      2,
    ),
    category: 'git',
  },
  {
    name: '文件系统',
    description: '本地文件系统访问标准配置',
    json: JSON.stringify(
      {
        mcpServers: {
          filesystem: {
            command: 'npx',
            args: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/allowed/files'],
          },
        },
      },
      null,
      2,
    ),
    category: 'filesystem',
  },
  {
    name: 'SQLite 数据库',
    description: 'SQLite 数据库访问标准配置',
    json: JSON.stringify(
      {
        mcpServers: {
          sqlite: {
            command: 'npx',
            args: ['-y', '@modelcontextprotocol/server-sqlite', '--db-path', './database.db'],
          },
        },
      },
      null,
      2,
    ),
    category: 'database',
  },
  {
    name: 'Web 搜索',
    description: '网络搜索功能标准配置',
    json: JSON.stringify(
      {
        mcpServers: {
          search: {
            command: 'npx',
            args: ['-y', '@modelcontextprotocol/server-web-search'],
            env: {
              SERPER_API_KEY: 'your_serper_api_key',
            },
          },
        },
      },
      null,
      2,
    ),
    category: 'search',
  },
]

// 验证输入
function validateInput() {
  if (!inputContent.value.trim()) {
    validationStatus.value = 'idle'
    validationError.value = null
    return
  }

  const result = validateJson(inputContent.value)
  if (result.isValid) {
    validationStatus.value = 'valid'
    validationError.value = null
  } else {
    validationStatus.value = 'invalid'
    validationError.value = result.error
  }
}

// 转换内容
async function convertContent() {
  if (!inputContent.value.trim() || validationStatus.value === 'invalid') {
    return
  }

  isConverting.value = true
  conversionStatus.value = 'validating'
  validationError.value = null
  conversionError.value = null

  try {
    // 验证JSON
    const validationResult = validateJson(inputContent.value)
    if (!validationResult.isValid) {
      validationError.value = validationResult.error
      conversionStatus.value = 'error'
      return
    }

    conversionStatus.value = 'converting'

    // 转换为TOML
    const result = jsonToToml(inputContent.value, addWindowsEnv.value, 'windows')

    if (result.success && result.toml) {
      outputContent.value = result.toml
      conversionStatus.value = 'success'
    } else {
      conversionError.value = result.error || null
      conversionStatus.value = 'error'
      outputContent.value = ''
    }
  } finally {
    isConverting.value = false
  }
}

// 复制输出内容
async function copyOutput() {
  if (outputContent.value) {
    try {
      const success = await copy(outputContent.value)
      if (success) {
        showSuccess('TOML内容已复制到剪贴板')
      } else {
        showError('无法复制到剪贴板')
      }
    } catch (error) {
      showError(error instanceof Error ? error.message : '复制失败')
    }
  }
}

// 清空输入内容
function clearInput() {
  inputContent.value = ''
  outputContent.value = ''
  conversionStatus.value = 'idle'
  validationStatus.value = 'idle'
  validationError.value = null
  conversionError.value = null
}

// 加载示例
function loadExample(example: McpExample) {
  inputContent.value = example.json
  outputContent.value = ''
  conversionStatus.value = 'idle'
  validationError.value = null
  conversionError.value = null

  // 验证加载的示例
  validateInput()

  // 滚动到编辑器区域
  const editorElement = document.querySelector('.editor-container')
  if (editorElement) {
    editorElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
  }
}

// 获取示例图标样式
function getExampleIconStyle(category: string) {
  const isDark = document.documentElement.classList.contains('dark')

  switch (category) {
    case 'git':
      return { backgroundColor: isDark ? '#f97316' : '#ea580c' }
    case 'filesystem':
      return { backgroundColor: isDark ? '#3b82f6' : '#2563eb' }
    case 'database':
      return { backgroundColor: isDark ? '#10b981' : '#059669' }
    case 'search':
      return { backgroundColor: isDark ? '#8b5cf6' : '#7c3aed' }
    case 'storage':
      return { backgroundColor: isDark ? '#f59e0b' : '#d97706' }
    case 'utility':
    default:
      return { backgroundColor: isDark ? '#6366f1' : '#4f46e5' }
  }
}
</script>

<style scoped>
/* 组件特定样式已在 main.css 中定义 */

/* 水平滚动示例卡片样式 */
.example-card-horizontal {
  padding: 1rem;
  background-color: var(--bg-secondary);
  border: 1px solid var(--border-primary);
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all var(--transition-normal);
  position: relative;
  overflow: hidden;
}

.example-card-horizontal::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, var(--primary-500), var(--accent-500));
  transform: scaleX(0);
  transition: transform var(--transition-normal);
}

.example-card-horizontal:hover {
  background-color: var(--hover-primary);
  border-color: var(--border-secondary);
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
}

.example-card-horizontal:hover::before {
  transform: scaleX(1);
}

.example-card-horizontal:active {
  transform: translateY(0);
}

/* 移动端示例卡片样式 */
.example-card-mobile {
  padding: 0.75rem;
  background-color: var(--bg-secondary);
  border: 1px solid var(--border-primary);
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all var(--transition-normal);
  position: relative;
  overflow: hidden;
}

.example-card-mobile::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, var(--primary-500), var(--accent-500));
  transform: scaleX(0);
  transition: transform var(--transition-normal);
}

.example-card-mobile:hover {
  background-color: var(--hover-primary);
  border-color: var(--border-secondary);
  box-shadow: var(--shadow-sm);
  transform: translateY(-1px);
}

.example-card-mobile:hover::before {
  transform: scaleX(1);
}

.example-card-mobile:active {
  transform: translateY(0);
}

/* 隐藏滚动条但保持滚动功能 */
.scrollbar-hide {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.scrollbar-hide::-webkit-scrollbar {
  display: none;
}

/* 文本截断样式 */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 触摸设备优化 */
@media (hover: none) and (pointer: coarse) {
  .example-card-horizontal:active,
  .example-card-mobile:active {
    background-color: var(--hover-primary);
    border-color: var(--border-secondary);
    box-shadow: var(--shadow-sm);
  }
}

/* 高对比度模式优化 */
@media (prefers-contrast: high) {
  .example-card-horizontal,
  .example-card-mobile {
    border-width: 2px;
  }

  .example-card-horizontal:hover,
  .example-card-mobile:hover {
    border-width: 3px;
  }
}

/* 减少动画偏好支持 */
@media (prefers-reduced-motion: reduce) {
  .example-card-horizontal,
  .example-card-mobile {
    transition: none;
  }

  .example-card-horizontal:hover,
  .example-card-mobile:hover {
    transform: none;
  }
}
</style>
